package com.example.GroovyScriptExample.controller;

import java.util.Date;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/nashorn")
public class NashornScriptController {
	ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

	@RequestMapping(value="/toParse",method = RequestMethod.POST)
	public String parseScript(String pamarstr, String dnumstr,HttpServletRequest request) throws ScriptException, NoSuchMethodException {
		String retstr = "";
		Double dnum = Double.valueOf(dnumstr);
		System.out.println("Date:"+new Date().toString()+"------"+"pamarstr:"+pamarstr+"----"+"dnum:"+dnum);
		if (null == pamarstr || pamarstr.length() == 0) {
			pamarstr = "123456789";
			System.out.println("paramstr：数据传入为空，修改为默认值 123456789");
		}
		if (null == dnum || dnum == 0.0) {
			dnum = 123456789.0;
			System.out.println("dnum：数据传入为空或为0，修改为默认值 123456789.0");
		}
		String script = sbr.toString().replaceAll("\\$\\{pamarstr\\}", pamarstr).replaceAll("\\$\\{dnum\\}", String.valueOf(dnum));
		engine.eval(script);
		Invocable invoke = (Invocable) engine;
		retstr = String.valueOf(invoke.invokeFunction("fun_js"));
		System.out.println(retstr);
		return retstr;
	}

	/**
	 * 获取字符串参数 String 的前 3个字符以及后 3个字符 然后拼接在 ":字符串变量:" 该字符串左右，
	 * 对double 进行 乘方 操作
	 * 并把两个参数的结果 通过 ";" 拼接起来成为新的字符串并返回
	 */
	String sbr = new String("function fun_js(){ "
			+ "var str=':字符串变量:'	; " 
			+ "var start3 = '${pamarstr}'.substr(0,3); "
			+ "var end3 = '${pamarstr}'.substr(-3); " 
			+ "str = start3+str+end3; "
			+ "var dnum = ${dnum}; "
			+ "return str+';'+Math.pow(dnum,2);"
			+ "}");
	
}
